package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author lmh
 * @since 2024-09-06
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeItemMapper serveItemMapper;
    @Autowired
    private RegionMapper regionMapper;

    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    @Override
    public void batchInsert(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        // 1. 判断数据是否为空 如果数据为空则抛出异常
        if (CollectionUtil.isEmpty(serveUpsertReqDTOList)) {
            throw new ForbiddenOperationException("数据为空不允许新增区域服务");
        }
        // 2. 遍历list 得到每一个需要新增的数据
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {

            // 3. 根据服务项的id查询服务项的数据 然后判断数据是否存在 如果不存在则抛出异常
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            if (ObjectUtil.isEmpty(serveItem)) {
                throw new ForbiddenOperationException("服务项目为空不允许新增区域服务");
            }
            // 4.继续判断服务状态是否合法 如果不合法则抛出异常
            if (serveItem.getActiveStatus() == FoundationStatusEnum.INIT.getStatus() ||
                    serveItem.getActiveStatus() == FoundationStatusEnum.DISABLE.getStatus()) {
                throw new ForbiddenOperationException("服务项目状态不对不允许新增区域服务");
            }
            // 5.查询当前区域是否已经上架了当前的服务 如果上架了 则抛出异常
            Integer count = lambdaQuery()
                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                    .count();
            if (count > 0) {
                throw new ForbiddenOperationException("当前区域已经上架了该服务 不允许重复上架");
            }
            // 6. 根据区域的id查询区域编码 然后设置数据
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            // 7.调用mapper插入数据
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }

    @Override
    public void update(Long id, BigDecimal price) {
        boolean flag = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        // 如果更新失败 抛出异常
        if (!flag) {
            throw new CommonException("数据更新失败");
        }
    }

    @Override
    @Transactional
    public Serve onSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //上架状态
        Integer saleStatus = serve.getSaleStatus();
        //草稿或下架状态方可上架
        if (!(saleStatus == FoundationStatusEnum.INIT.getStatus() || saleStatus == FoundationStatusEnum.DISABLE.getStatus())) {
            throw new ForbiddenOperationException("草稿或下架状态方可上架");
        }
        //服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if (ObjectUtil.isNull(serveItem)) {
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        //服务项的启用状态
        Integer activeStatus = serveItem.getActiveStatus();

        //服务项为启用状态方可上架
        if (!(FoundationStatusEnum.ENABLE.getStatus() == activeStatus)) {
            throw new ForbiddenOperationException("服务项为启用状态方可上架");
        }

        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if (!update) {
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("服务不存在");
        }
        //启用状态
        Integer saleStatus = serve.getSaleStatus();

        //1.删除校验：只有草稿状态方可删除
        if (!(FoundationStatusEnum.INIT.getStatus() == saleStatus)) {
            throw new ForbiddenOperationException("只有草稿状态方可删除");
        }

        //2.根据id删除
        baseMapper.deleteById(id);
    }

    @Override
    public Serve offSale(Long id) {
        // 1. 根据区域服务id查询服务
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }

        // 2. 只有上架状态才可下架
        Integer saleStatus = serve.getSaleStatus();
        if (!(saleStatus == FoundationStatusEnum.ENABLE.getStatus())) {
            throw new ForbiddenOperationException("上架状态方可下架");
        }

        // 3. 根据服务项id查询服务项
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if (ObjectUtil.isEmpty(serveItem)) {
            throw new ForbiddenOperationException("所属服务项不存在");
        }

        // 4.服务项为草稿状态不可下架
        Integer activeStatus = serveItem.getActiveStatus();
        if (activeStatus == FoundationStatusEnum.INIT.getStatus()) {
            throw new ForbiddenOperationException("服务项为草稿状态方不可下架");
        }

        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if (!update) {
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    public Serve onHot(Long id) {
        // 1.根据id查询区域服务
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(serve)) {
            throw new CommonException("区域服务不存在");
        }
        // 2.查询 区域服务状态为上架状态 方可设置热门
        Integer saleStatus = serve.getSaleStatus();
        if ((saleStatus == FoundationStatusEnum.INIT.getStatus() || saleStatus == FoundationStatusEnum.DISABLE.getStatus())) {
            throw new ForbiddenOperationException("草稿或下架状态不可设置热门");
        }
        // 3. 根据id查询服务项
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if (ObjectUtil.isEmpty(serveItem)) {
            throw new CommonException("服务项目不存在");
        }
        // 4. 只有为启用状态，才能设置为热门
        Integer activeStatus = serveItem.getActiveStatus();
        if (!(activeStatus == FoundationStatusEnum.ENABLE.getStatus())) {
            throw new ForbiddenOperationException("服务项不为启动状态不可设置热门");
        }

        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if (!update) {
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    public Serve offHot(Long id) {
        // 1.根据id查询区域服务
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(serve)) {
            throw new CommonException("区域服务不存在");
        }

        // 2.查询 区域服务状态
        // TODO 什么状态都可取消热门
        // Integer saleStatus = serve.getSaleStatus();
        // if ((saleStatus == FoundationStatusEnum.INIT.getStatus() || saleStatus == FoundationStatusEnum.DISABLE.getStatus())) {
        //     throw new ForbiddenOperationException("草稿或下架状态不可设置热门");
        // }

        // 3. 根据id查询服务项
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if (ObjectUtil.isEmpty(serveItem)) {
            throw new CommonException("服务项目不存在");
        }

        // 4. 只有为启用状态，才能设置为热门
        // TODO 什么状态都可取消热门
        // Integer activeStatus = serveItem.getActiveStatus();
        // if (!(activeStatus == FoundationStatusEnum.ENABLE.getStatus())) {
        //     throw new ForbiddenOperationException("服务项不为启动状态不可设置热门");
        // }

        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationStatusEnum.INIT.getStatus())
                .update();
        if (!update) {
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }
}
